<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="文件名称">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入关键字"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="关键字" prop="keyword">
        <el-input
          v-model="queryParams.keyword"
          placeholder="请输入关键字"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="文件状态" prop="statusValue">
        <el-select v-model="queryParams.statusValue" placeholder="请选择文件状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_file_record_status_history"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="printBox"
          v-hasPermi="['system:fileHistory:print']"
        >打印</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table
      fit
      v-loading="loading"
      border
      :data="dataList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="文件名称"
        min-width="300"
        prop="fileManager.fileName"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="文件预览" prop="fileCode" :show-overflow-tooltip="true" width="100">
        <template slot-scope="scope">
          <!-- <div v-for="item in scope.row.fileManager.fileUrl.split(',')"> -->
          <!-- <pdf ref="pdfDom" :src="baseUrl + item" :page="currentPage" @num-pages="pageCount = $event"
          @page-loaded="currentPage = $event" @loaded="loadPdfHandler"></pdf>-->
          <!-- </div> -->
          <el-link
            type="primary"
            :href="baseUrl + item"
            target="_blank"
            v-for="item in scope.row.fileManager.fileUrl&&scope.row.fileManager.fileUrl.split(',')"
          >预览</el-link>
        </template>
      </el-table-column>
      <el-table-column min-width="100" label="文件状态" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.sys_file_record_status_history"
            :value="scope.row.statusValue"
          />
        </template>
      </el-table-column>
      <el-table-column label="领用数量" min-width="100" prop="num" :show-overflow-tooltip="true" />
      <el-table-column
        label="文件类型"
        min-width="120"
        prop="fileManager.fileTypeLabel"
        :show-overflow-tooltip="true"
      />

      <el-table-column
        min-width="100"
        label="申请人"
        prop="createByName"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="操作"
        align="center"
        width="200"
        fixed="right"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.statusValue == 1 && scope.row.isDraft"
            size="mini"
            type="text"
            v-hasPermi="['system:file:mySelfFileHistory:reset']"
            @click="handlAuditEase(scope.row, '撤销', 0)"
          >撤销</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 打印模板位置 -->
    <PrintBox
      :checkNum="8"
      :printRow="printList"
      :checkLabel="'checkLabel'"
      :isVertical="false"
      id="printBox"
      :isPageSize="false"
    >
      <template slot="title" slot-scope="scope">
        <div>化学试剂药品入库记录表 STET/B/07-1</div>
      </template>
      <template slot-scope="scope">
        <div>
          <div
            style="display: flex;align-items: center;justify-content: space-between;margin-top: 20px;"
          >
            <!-- <div>检测单位名称：苏州交通工程试验检测中心有限公司</div> -->
            <!-- <div style="padding-right: 200px;">记录编号：</div> -->
          </div>
        </div>
        <table
          style="border-collapse: collapse; table-layout: fixed"
          border="1"
          cellspacing="0"
          class="table-page"
        >
          <tr style="height: 5mm">
            <!-- <td style="width: 100mm">受控文件</td> -->
            <td style="width: 150mm">分发号</td>
            <td style="width: 120mm">领用人</td>
          </tr>
          <tr v-for="(e, i) in 15">
            <!-- <td>{{ scope.item.contentList[i] && scope.item.contentList[i].standardManager.standardCode }}</td> -->
            <td>{{ scope.item.contentList[i] && scope.item.contentList[i].distributionCode }}</td>
            <td>{{ scope.item.contentList[i] && scope.item.contentList[i].createByName }}</td>
            <!-- <td>{{ scope.item.contentList[i] }}</td> -->
            <!-- <td>{{ 23 }}</td> -->
            <!-- <td>{{ printList[i] && printList[i].createByName }}</td> -->
            <!-- <td>{{ scope.row.snhtandardManager.standardCode }}</td>
              <td>{{ scope.row.standardManager.standardName }}</td>
            <td>{{ scope.row.createByName }}</td>-->
          </tr>
        </table>
        <div class="page-bottom" style="page-break-after: always">
          <div class="desc">注：本表格自2021 年 6 月 1 日起生效</div>
        </div>
      </template>
    </PrintBox>

    <el-dialog :visible.sync="showCode" title="回收" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="归还人" prop="returnUserId">
          <UserDialog placeholder="请选择归还人" @change="changeUser" v-model="form.returnUserId"></UserDialog>
        </el-form-item>
      </el-form>
      <template slot="footer">
        <el-button size="mini" @click="showCode = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="saveFieldOption">确 定</el-button>
      </template>
    </el-dialog>
    <el-dialog title="审核" :visible.sync="openAudit" width="700px" append-to-body>
      <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="100px">
        <el-form-item label="审核结果" prop="optType">
          <el-radio-group v-model="formData.optType">
            <el-radio label="1">审核通过</el-radio>
            <el-radio label="2">审核不通过</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="formData.optType == 2" label="审核原因" prop="reason">
          <el-input
            v-model="formData.reason"
            placeholder="请输入审核原因"
            clearable
            :style="{ width: '100%' }"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="openAudit = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="审核记录" :visible.sync="auditLogShow" width="50%" append-to-body>
      <el-table fit :data="logList">
        <el-table-column label="操作描述" min-width="150" prop="optDesc" :show-overflow-tooltip="true" />
        <el-table-column label="操作类型" min-width="150" prop="optType" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.optType == 1
                ? 'success'
                : scope.row.optType == 2
                  ? 'danger'
                  : 'warning'
                "
            >
              {{
              scope.row.optType == 1
              ? "通过"
              : scope.row.optType == 2
              ? "驳回"
              : "撤销"
              }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" min-width="150" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.sys_file_record_status_history"
              :value="scope.row.optStatus"
            />
          </template>
        </el-table-column>
        <el-table-column label="理由" min-width="150" prop="reason" :show-overflow-tooltip="true" />
        <el-table-column
          label="创建者"
          min-width="150"
          prop="createByName"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="创建时间"
          min-width="150"
          prop="createTime"
          :show-overflow-tooltip="true"
        />
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="auditLogShow = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
  <script>
import {
  fileGetList,
  fileGetDel,
  fileGetAudit,
  updategfileGet,
  OptAuditList
} from "@/api/system/fileManagerRecord.js";
import printStyle from "@/utils/print.js";
import store from "@/store";
// 单组件引用
import pdf from "vue-pdf";

export default {
  name: "fileManagerRecord",
  dicts: ["sys_file_record_status_history"],
  // 然后在component中进行注册
  components: {
    pdf
  },
  data() {
    return {
      baseUrl: this.$VUE_APP_IMG_API,
      openAudit: false,
      formData: {
        optType: "1"
      },
      pageCount: 0, // pdf文件总页数
      currentPage: 1, // pdf文件页码
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 角色表格数据
      dataList: [],
      // 弹出层标题
      // 日期范围
      dateRange: [],
      // 数据范围选项
      queryParams: {
        pageNum: 1,
        keyword: undefined,
        fileTypeValue: undefined,
        statusValue: undefined,
        pageSize: 10
      },
      showCode: false,
      form: {},
      infos: [],
      rules: {
        reason: [
          {
            required: true,
            message: "备注不能为空",
            trigger: "blur"
          }
        ],
        returnUserId: [
          {
            required: true,
            message: "请选择归还人",
            trigger: "change"
          }
        ]
      },
      current: {},
      auditLogShow: false,
      logList: []
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 获取文件名称
    getFileName(name) {
      // 如果是url那么取最后的名字 如果不是直接返回
      if (name.lastIndexOf("/") > -1) {
        return name.slice(name.lastIndexOf("/") + 1);
      } else {
        return name;
      }
    },
    handleLog(row) {
      OptAuditList({ busType: 1, busId: row.fileGetId }).then(res => {
        this.logList = res.data;
        this.auditLogShow = true;
      });
    },
    // 审批弹出
    handlAudit(row) {
      this.formData = {
        optType: "1",
        fileGetId: row.fileGetId,
        preAudit: row.statusValue,
        reason: ""
      };
      this.openAudit = true;
    },
    handlAuditEase(row, text, flag = 1) {
      let query = {
        optType: flag,
        fileGetId: row.fileGetId,
        preAudit: row.statusValue,
        reason: ""
      };
      this.$modal
        .confirm(
          "是否" + text + '名称为"' + row.fileManager.fileName + '"的数据项？'
        )
        .then(function() {
          return fileGetAudit(query);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("操作成功");
        })
        .catch(() => {});
    },
    printBox() {
      //infos  勾选的数据 如果有勾选就打印勾选。
      if (this.infos.length) {
        this.printList = [
          {
            contentList: this.infos
          }
        ];
      } else {
        //反之打印当前整个列表
        this.printList = [
          {
            contentList: this.dataList
          }
        ];
      }
      let year = new Date().getFullYear();
      console.log(year);
      console.log(this.printList, " this.printList");
      this.printList.forEach((item, index) => {
        item.contentList.forEach(lab => {
          const randomNum = Math.floor(Math.random() * 10000);
          let serialNumber = `BZ${randomNum.toString().padStart(4, "0")}`;
          lab.distributionCode = "";
          this.$set(lab, "distributionCode", year + serialNumber);
        });

        // item.distributionCode = year + 'BZ' + 1234
      });
      setTimeout(() => {
        document.title = "化学试剂药品入库记录表 STET/B/07-1";
        this.$print({
          printable: "printBox", //打印区域id
          type: "html", //打印类型是html
          scanStyles: false,
          targetStyles: ["*"],
          style: this.workStyle(),
          onPrintDialogClose: () => {
            document.title = process.env.VUE_APP_TITLE;
          }
        });
      }, 500);
    },
    // 可以自定义样式  printStyle 是公共样式 切勿私自修改
    workStyle() {
      return `${printStyle}
          table,
          table tr th,
          table tr td {
            height:17mm;
            padding: 0px;
            font-size: 12px;
          }
          .desc{
          text-align: left; font-size: 12px; margin-top: 10px
        }
              .df {
                  display: flex;
                }
        `;
    },
    /* 回收 */
    handleReturn(row) {
      let query = {
        optType: row.isDraft ? 1 : 2,
        fileGetId: row.fileGetId,
        preAudit: row.statusValue,
        reason: ""
      };
      this.$modal
        .confirm(
          "是否回收" + '名称为"' + row.fileManager.fileName + '"的数据项？'
        )
        .then(function() {
          return fileGetAudit(query);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("操作成功");
        })
        .catch(() => {});
    },
    submitForm: function() {
      this.$refs["elForm"].validate(valid => {
        if (valid) {
          let query = JSON.parse(JSON.stringify(this.formData));
          fileGetAudit(query).then(response => {
            this.$modal.msgSuccess("审核成功");
            this.openAudit = false;
            this.getList();
          });
        }
      });
    },
    changeUser(e) {
      this.form.returnUser = e.nickName;
    },
    // 回收
    saveFieldOption() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.fileGetId = this.current.fileGetId;
          this.form.returnTime = this.parseTime(new Date());
          this.form.optReturnUser = store.state.user.nickName;
          this.form.optReturnUserId = store.state.user.id;
          this.form.sureReturnTime = this.parseTime(new Date());
          this.form.statusValue = 4;
          updategfileGet(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.showCode = false;
            this.getList();
          });
        }
      });
    },
    userSelect() {
      userSelect().then(response => {
        this.userList = response.data;
      });
    },
    getList() {
      this.loading = true;
      // this.queryParams.userId = store.state.user.id
      this.queryParams.person = 1;
      fileGetList(this.addDateRangeTime(this.queryParams, this.dateRange)).then(
        response => {
          this.dataList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    handleDetail(row) {
      this.$router.push("./addFile?isInfo=true&id=" + row.fileManagerId);
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.fileManagerId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
      this.infos = selection;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$router.push("./addFile");
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const configId = row.fileManagerId || this.ids;
      this.$router.push("./addFile?isEdit=true&id=" + configId);
    },
    handleExport() {
      this.download(
        "system/fileManager/export",
        {
          ...this.queryParams
        },
        `文件记录表_${this.parseTime(new Date().getTime(), "{y}-{m}-{d}")}.xlsx`
      );
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.fileGetId || this.ids;
      this.$modal
        .confirm(
          '是否确认删除名称为"' + row.fileManager.fileName + '"的数据项？'
        )
        .then(function() {
          return fileGetDel(userIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    }
  }
};
</script>
  